package stock;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.client.RestTemplate;
import stock.bean.AliExcelData;
import stock.bean.DemoDataListener;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class DownLoadFile {


    public static void main(String[] args)  {
//        String url = "https://in-20170801162519677-lotpwyqx7z.oss-cn-shanghai.aliyuncs.com/video/5a5d82a-1648353b0a1-0004-9e86-9ff-24e18.mp4?Expires=1730885087&OSSAccessKeyId=LTAIwkKSLcUfI2u4&Signature=atF56g63zFDG3ekf1h1%2FmpSOKRw%3D";
//        String normalUrl = "http://vod.yketang.com/6d2317dd58e44988a434efd2ccefac42/091c3284e06543059d2bb3de9341fa4a-5287d2089db37e62345123a1be272f8b.mp4";
//        String fileName = "京东大学电商学院宣传片（更新）~1";
//        download(url,0,fileName);
//        download(normalUrl,1,fileName);
        String fileName = "C:\\Users\\AOC\\Desktop\\云课堂视频4.xlsx";
        DemoDataListener listener = new DemoDataListener();
        EasyExcel.read(fileName,AliExcelData.class,listener).sheet(0).doRead();
        List<AliExcelData> cachedDataList = listener.getCachedDataList();

        int corePoolSize = 10;
        // 准备线程池
        ExecutorService executorService = Executors.newFixedThreadPool(corePoolSize);


        for (int i = 0; i < cachedDataList.size(); i++) {
            AliExcelData aliExcelData = cachedDataList.get(i);
            log.info("正在下载第{}个,名称为{}",i,aliExcelData.getFileName());
            int finalI = i;
            executorService.execute(()->{
                if (!StringUtils.isBlank(aliExcelData.getOriginUrl())){
                    download(aliExcelData.getOriginUrl(),0,aliExcelData.getFileName(), finalI);
                }
            });
            executorService.execute(()->{
                if (!StringUtils.isBlank(aliExcelData.getNormalUrl())){
                    download(aliExcelData.getNormalUrl(),1,aliExcelData.getFileName(), finalI);
                }
            });

        }


    }


    /**
     * 下载视频
     * @param url url
     * @param type 类型 0-原视频 1-标清
     * @param fileName 文件名
     */
    private static void download(String url ,Integer type , String fileName,Integer size) {
        String path = "E:\\安博文件\\0001.云课堂服务器备份\\video";
        if (type == 1){
            path += "\\normal";
        }else {
            path+= "\\origin";
        }
        String suffix = "";
        if (url.contains("?")) {
            String temUrl = url.substring(0,url.indexOf("?"));
            suffix = temUrl.substring(temUrl.lastIndexOf("."));
        }else {
            suffix = url.substring(url.lastIndexOf("."));
        }
        if (!fileName.endsWith(suffix)) {
            fileName += suffix;
        }
        // 指定目的路径，获取到输出流
        File out = new File(path);
        if (!out.exists()) {
            out.mkdirs();
        }
        File video = new File(out.getPath()+ "\\" +fileName);
        if (video.exists()){
            log.info("第{}个:{}视频{}存在跳过下载",size,fileName,type);
            return;
        }

        try {
            //构造下载
            URL urlConnect = new URL(url);
            URLConnection con = urlConnect.openConnection();
            con.setConnectTimeout(20 * 1000);
            log.info("第{}个:开始下载{}视频文件名为：{}",size,type,fileName);
            long start = System.currentTimeMillis();
            // 通过输入流读取文件内容
            InputStream inputStream = con.getInputStream();

            OutputStream outputStream = Files.newOutputStream(Paths.get(out.getPath() + "\\" + fileName));

            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1){
                // 通过输出流，下载到本地
                outputStream.write(bytes,0,len);
                // 刷新
//                outputStream.flush();
            }

            // 5、关闭资源
            outputStream.close();
            inputStream.close();
            log.info("第{}个:下载完成耗时:{}秒",size,(System.currentTimeMillis() - start) / 1000);
        } catch (Exception e) {
            log.error("下载文件异常，文件名：{}，url为：{}",fileName,url,e);
        }
    }

}
